package com.smart.campus.web.controller.school;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.io.resource.ClassPathResource;
import com.smart.campus.school.domain.ExamRoomSchedule;
import com.smart.campus.school.domain.ExamRoomStudents;
import com.smart.campus.school.service.IExamRoomScheduleService;
import com.smart.campus.school.service.IExamRoomStudentsService;
import com.smart.campus.school.service.impl.ExamRoomStudentsServiceImpl;
import com.smart.campus.web.utils.PdfUtil;
import com.smart.campus.web.utils.SchoolUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smart.campus.common.annotation.Log;
import com.smart.campus.common.enums.BusinessType;
import com.smart.campus.school.domain.ExamRoomClasses;
import com.smart.campus.school.service.IExamRoomClassesService;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.poi.ExcelUtil;
import com.smart.campus.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 考场场次教室信息Controller
 * 
 * @author Zhihe.Li
 * @date 2020-06-04
 */
@Controller
@RequestMapping("/school/examRoomClasses")
public class ExamRoomClassesController extends BaseController
{
    private String prefix = "school/examRoomClasses";

    @Autowired
    private IExamRoomScheduleService examRoomScheduleService;

    @Autowired
    private IExamRoomClassesService examRoomClassesService;

    @Autowired
    private IExamRoomScheduleService scheduleService;
    @Autowired
    private IExamRoomStudentsService examRoomStudentsService;

    @RequiresPermissions("school:examRoomClasses:view")
    @GetMapping("/{scheduleId}")
    public String examRoomClasses(@PathVariable Long scheduleId,ModelMap mmap)
    {
        ExamRoomSchedule examSchedule = scheduleService.selectExamRoomScheduleById(scheduleId);
        mmap.put("dule",examSchedule);
        return prefix + "/examRoomClasses";
    }

    /**
     * 查询考场场次教室信息列表
     */
    @RequiresPermissions("school:examRoomClasses:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ExamRoomClasses examRoomClasses)
    {
        startPage();
        List<ExamRoomClasses> list = examRoomClassesService.selectExamRoomClassesList(examRoomClasses);
        return getDataTable(list);
    }

    /**
     * 导出考场场次教室信息列表
     */
    @RequiresPermissions("school:examRoomClasses:export")
    @Log(title = "考场场次教室信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ExamRoomClasses examRoomClasses)
    {
        List<ExamRoomClasses> list = examRoomClassesService.selectExamRoomClassesList(examRoomClasses);
        ExcelUtil<ExamRoomClasses> util = new ExcelUtil<ExamRoomClasses>(ExamRoomClasses.class);
        return util.exportExcel(list, "examRoomClasses");
    }

    /**
     * 新增考场场次教室信息
     */
    @GetMapping("/add/{scheduleId}")
    public String add(@PathVariable Long scheduleId,ModelMap mmap)
    {
        ExamRoomSchedule examSchedule = scheduleService.selectExamRoomScheduleById(scheduleId);
        mmap.put("dule",examSchedule);
        return prefix + "/add";
    }

    /**
     * 新增保存考场场次教室信息
     */
    @RequiresPermissions("school:examRoomClasses:add")
    @Log(title = "考场场次教室信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ExamRoomClasses examRoomClasses)
    {
        return toAjax(examRoomClassesService.insertExamRoomClasses(examRoomClasses));
    }

    /**
     * 修改考场场次教室信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ExamRoomClasses examRoomClasses = examRoomClassesService.selectExamRoomClassesById(id);
        mmap.put("examRoomClasses", examRoomClasses);
        return prefix + "/edit";
    }

    /**
     * 修改保存考场场次教室信息
     */
    @RequiresPermissions("school:examRoomClasses:edit")
    @Log(title = "考场场次教室信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ExamRoomClasses examRoomClasses)
    {
        return toAjax(examRoomClassesService.updateExamRoomClasses(examRoomClasses));
    }

    /**
     * 打印考场安排
     */
    @GetMapping("/print/{id}")
    public String print(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ExamRoomClasses room = examRoomClassesService.selectExamRoomClassesById(id);

        ExamRoomSchedule examRoomSchedule = examRoomScheduleService.selectExamRoomScheduleById(room.getScheduleId());

        ExamRoomClasses classes = new ExamRoomClasses();
        classes.setScheduleId(id);
        List<ExamRoomClasses> roomList = new ArrayList<>();
        ExamRoomStudents students = new ExamRoomStudents();
        students.setClazzId(id);
        List<ExamRoomStudents> studentsList = examRoomStudentsService.selectExamRoomStudentsList(students);
        room.setStudentsList(studentsList);
        roomList.add(room);
        examRoomSchedule.setList(roomList);
        if(CollectionUtils.isNotEmpty(studentsList)){//学生是否为空
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/png");
            OutputStream out = null;
            try {
                ClassPathResource resource = new ClassPathResource("");
                String temp = resource.getFile().getAbsolutePath()+"/temp/";
                File file = new File(temp);
                if(!file.exists()){
                    file.mkdirs();
                }
                String fullName = PdfUtil.createExamSitesPdf(examRoomSchedule,temp);
                logger.info(fullName);
                File f0 = new File(fullName);
                if(f0.exists()){
                    String headerKey = "Content-Disposition";
                    String headerValue = String.format("attachment; filename=\"%s\"",
                            f0.getName());
                    response.setHeader(headerKey, headerValue);
                    InputStream myStream = new FileInputStream(fullName);
                    IOUtils.copy(myStream, response.getOutputStream());
                }
                response.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(out!=null)
                        out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 删除考场场次教室信息
     */
    @RequiresPermissions("school:examRoomClasses:remove")
    @Log(title = "考场场次教室信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(examRoomClassesService.deleteExamRoomClassesByIds(ids));
    }


    @GetMapping("/getRoomList/{id}")
    @ResponseBody
    public List<ExamRoomClasses> getScheduleList2(@PathVariable("id") Long scheduleId) {
        ExamRoomClasses roomClasses = new ExamRoomClasses();
        roomClasses.setScheduleId(scheduleId);
        List<ExamRoomClasses> list = examRoomClassesService.selectExamRoomClassesList(roomClasses);
        return list;
    }
}
